#include "dbconnect.h"
#include "ui_dbconnect.h"
#include <QSettings>
#include <QSqlDatabase>
#include <QMessageBox>

DBConnect::DBConnect(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DBConnect)
{
    ui->setupUi(this);

    loadSavedValues();

    connect(ui->loginButton, SIGNAL(clicked()),
            this, SLOT(login()));
    connect(ui->exitButton, SIGNAL(clicked()),
            this, SLOT(reject()));
}

DBConnect::~DBConnect()
{
    delete ui;
}

void DBConnect::loadSavedValues()
{
    QSettings s("romix.lab", "acs");
    QString server = s.value("db/server").toString();
    int port = s.value("db/port", 3306).toInt();
    QString user = s.value("db/user").toString();
    ui->serverEdit->setText(server);
    ui->portSpin->setValue(port);
    ui->loginEdit->setText(user);
}

void DBConnect::saveValues()
{
    QSettings s("romix.lab", "acs");
    s.setValue("db/server", ui->serverEdit->text());
    s.setValue("db/port", ui->portSpin->value());
    s.setValue("db/user", ui->loginEdit->text());
}

void DBConnect::login()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(ui->serverEdit->text());
    db.setUserName(ui->loginEdit->text());
    db.setPassword(ui->passEdit->text());
    db.setDatabaseName("acs");
    if (db.open()) {
        saveValues();
        accept();
    } else {
        QMessageBox::critical(this, tr("Error"), tr("Can't connect to db! Try again."));
    }
}
